const fs = require('fs');
const hub = require('./hub');
const SubscriptionManager = require('./dts/subscriptionManager');


let fakeImage = fs.readFileSync('./fake.png');

var ruleMap = require('./ruleMap');
var ProfileRule = require('./rules/profileRule');
var ArticleRule = require('./rules/acticleRule');
var CommentRule = require('./rules/CommentRule');

const mq = require('./mq/mq');

_args = {
    msgs: [],
    mgr: new SubscriptionManager(),
    mq: mq,
    hub: hub.connection
};

ruleMap.use(new ProfileRule(_args));
ruleMap.use(new ArticleRule(_args));
ruleMap.use(new CommentRule(_args));

module.exports = {
    summary: 'wechat proxy',

    *beforeSendRequest(req) {
        let accept = req.requestOptions.headers['Accept'];

        if (accept && accept.indexOf('image') !== -1
            && (
                req.url.indexOf('mmbiz.qpic.cn/') !== -1 ||
                req.url.indexOf('mmbiz.qpic.cn/mmbiz_') !== -1 ||
                req.url.indexOf('mmbiz.qpic.cn/mmbiz_') !== -1
            )) {
            return {
                response: {
                    statusCode: 200,
                    header: { 'content-type': 'image/png' },
                    body: fakeImage
                }
            };
        }

        // if (req.url.indexOf('mp.weixin.qq.com/mp/profile_ext?') > -1 &&
        //     req.requestOptions.method === 'GET') {
            
        //     var origin = new URL(req.url);
        //     var action = origin.searchParams.get('action');

        //     if (action && action === 'getmsg') {
        //         origin.searchParams.set('offset', 0);
        //         origin.searchParams.set('count', 1000);

        //         logger.file(origin.href + '\r\n');

        //         return {
        //             url: origin.href
        //         };
        //     }
        // }

        // ruleMap.fake(req);
    },

    *beforeSendResponse(req, resp) {
        return ruleMap.execute(req, resp);
    }
};